package com.wzl.thread.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 创建线程数，并且可以重复用
 *
 *  创建固定线程数量的线程池
 *  创建一个固定大小的线程池，该方法可指定线程池的固定大小，对于超出的线程会在LinkedBlockingQueue队列中等待
 *  核心线程数可以指定，线程空闲时间为0
 *
 * @author weizhongli
 * @since 2022-09-19 10:39
 */
@Slf4j
public class TcNewFixedThreadPool {

    /**
     * newFixedThreadPool方法
     */
    public static void NoFactoryPool(){
        //1.使用工厂类获取线程池对象
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //2.提交任务
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            executorService.submit(() ->{
                log.info("线程执行啦.......哈哈哈哈哈哈" + finalI + "----" + Thread.currentThread().getName());
            });
        }
    }

    /**
     * newFixedThreadPool (ThreadFactory threadFactory)方法
     */
    public static void factoryPool(){
        //1.使用工厂类获取线程池对象
        ExecutorService executorService = Executors.newFixedThreadPool(3,new ThreadFactory() {
            int n = 1;
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"自定义的线程名称" + n++);
            }
        });
        //2.提交任务
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            executorService.submit( () -> {
                log.info("线程执行啦.......哈哈哈哈哈哈" + finalI + "----" + Thread.currentThread().getName());
            });
        }
    }

}